//
//  ForumHomeVC.m
//  sensen_ios
//
//  Created by justiOS on 16/5/3.
//  Copyright © 2016年 pro. All rights reserved.
//

#import "ForumHomeVC.h"
// 控制器
#import "PostDetailVC.h" // 帖子详情
#import "ForumSectionVC.h" // 论坛版块分类页面
#import "SearchPostVC.h" // 搜索界面
#import "WaterForumSectionVC.h"// 水族（有子论坛的）专用
#import "ShopMessageVC.h"

// 视图
#import "CarouselView.h" // 轮播视图
#import "HomeSectionView.h" // 分栏视图
#import "ForcumHomeView.h"

// 单元格
#import "ShowCell.h" // 帖子概览单元格
#import "ForumModel.h"
@interface ForumHomeVC ()<UITableViewDelegate,UITableViewDataSource>
{
    UIScrollView *_scrollView; // 滑动视图
    
    CarouselView *_carouselView; // 顶部的图片视图
    ForcumHomeView *_wisdomView; // 森森智囊团
    ForcumHomeView *_procurementView; // 森森采购师
    ForcumHomeView *_designView; // 森森设计师
    ForcumHomeView *_shoppingView;//购物评论区
    UIScrollView *_buttonsScrollView; //跳转按钮滑动视图
    UITableView *_tableView; // 表视图
    NSString *_fup; //父论坛ID
}

@property (nonatomic, strong) NSMutableArray *itemsAry;
@property (nonatomic, strong) NSMutableArray *nameAry;
@end

@implementation ForumHomeVC

- (void)viewDidLoad {
    [super viewDidLoad];
    if (_itemsAry == nil) {
        _itemsAry = [[NSMutableArray alloc] init];
    }else{
        [_itemsAry removeAllObjects];
    }
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"休闲论坛";
    
    // 创建导航栏视图
    [self createRightBarButtonItems]; // 右侧搜索
    [self createLeftBarButtonItems]; // 左侧返回
    
    // 创建
    [self _createViews];
    [self _getCarouselImgs];
    [self _initData]; // 获取数据
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    // 显示标签栏
    MainTabBarController *main = (MainTabBarController *)self.tabBarController;
    [main showTabBar];
    
    // 获取子论坛
    [self _getForum];
}


- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}
#pragma mark - 创建视图
#pragma mark -- 创建导航栏视图 --
// 创建导航栏右侧按钮（搜索和消息）
- (void)createRightBarButtonItems {
//    
//    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
//    button.frame = CGRectMake(0, 0, 20, 20);
//    [button setBackgroundImage:[UIImage imageNamed:@"论坛首页_搜索"] forState:UIControlStateNormal];
//    [button addTarget:self action:@selector(_naviRightAction:) forControlEvents:UIControlEventTouchUpInside];
//    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
//    self.navigationItem.rightBarButtonItem = barButtonItem;
    NSArray *imgNames = @[@"论坛首页_消息通知", @"论坛首页_搜索"];
    NSMutableArray *items = [NSMutableArray array];
    for (int i = 0; i < imgNames.count; i ++) {
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(0, 0, 20, 20);
        [button setBackgroundImage:[UIImage imageNamed:imgNames[i]] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(_naviRightAction:) forControlEvents:UIControlEventTouchUpInside];
        button.tag = i + 1;
        
        UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
        [items addObject:barButtonItem];
    }
    
    self.navigationItem.rightBarButtonItems = items;

}

// 创建导航栏左侧按钮
- (void)createLeftBarButtonItems {
    
    // 返回
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame = CGRectMake(0, 0, 25/2, 43/2);
    [backButton setBackgroundImage:[UIImage imageNamed:@"导航栏_返回"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(_naviLeftAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *barButtonItem1 = [[UIBarButtonItem alloc] initWithCustomView:backButton];    
    self.navigationItem.leftBarButtonItems = @[barButtonItem1];

}
#pragma mark - 获取数据
- (void)_getForum{
    if (_nameAry == nil) {
        _nameAry = [[NSMutableArray alloc] init];
    }else{
        [_nameAry removeAllObjects];
    }
    //有子论坛的 父论坛id
    _fup = @"1";
    [BoyeHttpClient post:@"BY_ForumForum_query" apiVerson:100 params:@{@"fup":_fup} success:^(AFHTTPRequestOperation *operation, id result) {
    
        NSLog(@"%@",result);
        if(![result[@"list"] isKindOfClass:[NSNull class]]){
            NSArray *array = result[@"list"];
            for (NSDictionary *resultDic in array) {
                ForumModel *model = [[ForumModel alloc] initContentWithDic:resultDic];
                [_nameAry addObject:model];
            }
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"加载失败" withDuration:1.5];
        
    }];

}

- (void)_getCarouselImgs {
    // 获得轮播图
    NSDictionary *params = @{@"position" : @6057};
    [BoyeHttpClient post:@"BY_Picture_getURL" apiVerson:100 params:params success:^(AFHTTPRequestOperation *operation, id result) {
        // 轮播图不为空
        if (![result isKindOfClass:[NSNull class]]) {
            NSMutableArray *ary = [NSMutableArray array];
            for (NSDictionary *dic in result) {
                CarouselModel *model = [[CarouselModel alloc] initContentWithDic:dic];
                
                [ary addObject:model];
            }
            
            // 设置轮播图
            _carouselView.modelAry = ary;
        }
        // 轮播图为空
        else {
            // 轮播图为空，则传入一个元素的数组，让轮播图加载默认图片
            _carouselView.modelAry = nil;
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        // 失败
        [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",error.domain] withDuration:2];
    }];
}
- (void)_initData {
    
    self.view.userInteractionEnabled = NO;
    [SVProgressHUD showWithStatus:nil];
    [BoyeHttpClient post:@"BY_ForumForum_query" apiVerson:100 params:nil success:^(AFHTTPRequestOperation *operation, id result) {
        if(![result[@"thread_list"] isKindOfClass:[NSNull class]]){
            NSArray *array = result[@"thread_list"];
            for (NSDictionary *resultDic in array) {
                PostModel *model = [[PostModel alloc] initContentWithDic:resultDic];
                ShowCellLayout *layout = [[ShowCellLayout alloc] init];
                layout.model = model;
                [_itemsAry addObject:layout];
            }
            CGFloat tableHeight = 0;
            for (ShowCellLayout *layout in _itemsAry) {
                tableHeight += (layout.cellRect.size.height);
            }
            _tableView.height = tableHeight;
            // 遍历滑动视图的子视图，设置滑动范围
            
            _scrollView.contentSize = CGSizeMake(0, _tableView.bottom);
        }
        [_tableView reloadData];
        
        self.view.userInteractionEnabled = YES;
        [SVProgressHUD dismiss];
        
        NSLog(@"%@",result);
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"加载失败" withDuration:1.5];
        self.view.userInteractionEnabled = YES;
        
    }];
}
#pragma mark -- 创建子视图 --
- (void)_createViews {
    
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64)];
    _scrollView.backgroundColor = [UIColor colorWithWhite:0.95 alpha:1];
    _scrollView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:_scrollView];
    
    [self _createTopViews]; // 顶部视图，
    [self _createButtons]; // 跳转按钮
    [self _initTableView]; // 表视图
    
    // 遍历滑动视图的子视图，设置滑动范围
    UIView *lastView = _scrollView.subviews.lastObject;
    _scrollView.contentSize = CGSizeMake(0, lastView.bottom);
    
}
- (void)_createTopViews {
    
    CGFloat x, y, width, height;
    x = 0;
    y = 0;
    width = SCREEN_WIDTH / 4;
    height = SCREEN_WIDTH / 5;
    // 森森智囊团
    _wisdomView = [[ForcumHomeView alloc] initWithFrame:CGRectMake(x, y, width, height) mulriple:0.55];
    _wisdomView.backgroundColor = rgba(230, 230, 230, 1);
    _wisdomView.title = @"森森智囊团";
    _wisdomView.imgName = @"论坛首页_森森智囊团";
    _wisdomView.titleColor = rgba(50, 142, 156, 1);
    [_scrollView addSubview:_wisdomView];
    UITapGestureRecognizer *recruitModeratorTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(_recruitModeratorAction:)];
    [_wisdomView addGestureRecognizer:recruitModeratorTap];
    
    // 森森采购师
    x = SCREEN_WIDTH / 4;
    _procurementView = [[ForcumHomeView alloc] initWithFrame:CGRectMake(x, y, width, height) mulriple:0.55];
    _procurementView.backgroundColor = rgba(230, 230, 230, 1);
    _procurementView.title = @"森森采购师";
    _procurementView.imgName = @"论坛首页_森森采购师";
    _procurementView.titleColor = rgba(288, 0, 126, 1);
    [_scrollView addSubview:_procurementView];
    UITapGestureRecognizer *postAndCouponsTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(_postAndCouponsAction:)];
    [_procurementView addGestureRecognizer:postAndCouponsTap];
    
    // 森森设计师
     x = SCREEN_WIDTH / 4 * 2;
    _designView = [[ForcumHomeView alloc] initWithFrame:CGRectMake(x, y, width, height) mulriple:0.55];
    _designView.backgroundColor = rgba(230, 230, 230, 1);
    _designView.title = @"森森设计师";
    _designView.imgName = @"论坛首页_森森设计师";
    _designView.titleColor = rgba(0, 149, 229, 1);
    [_scrollView addSubview:_designView];
    UITapGestureRecognizer *showAndAwardTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(_showAndAwardAction:)];
    [_designView addGestureRecognizer:showAndAwardTap];
    
    
    //购物评论区
    x = SCREEN_WIDTH / 4 * 3;
    _shoppingView = [[ForcumHomeView alloc] initWithFrame:CGRectMake(x, y, width, height) mulriple:0.55];
    _shoppingView.backgroundColor = rgba(230, 230, 230, 1);
    _shoppingView.title = @"购物评论区";
    _shoppingView.imgName = @"论坛首页_09";
    _shoppingView.titleColor = rgba(255, 94, 116, 1);
    [_scrollView addSubview:_shoppingView];
    UITapGestureRecognizer *shoppingTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(_shoppingAction:)];
    [_shoppingView addGestureRecognizer:shoppingTap];

    
    // 顶部轮播视图
    x = 0;
    y = _wisdomView.bottom;
    width = SCREEN_WIDTH;
    height = width / 2;
    _carouselView = [[CarouselView alloc] initWithFrame:CGRectMake(x, y, width, height) timerDuration:3 carouselAmount:3];
    [_scrollView addSubview:_carouselView];
    
}
- (void)_createButtons{
    _buttonsScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, _carouselView.bottom, SCREEN_WIDTH, SCREEN_WIDTH / 5)];
    _buttonsScrollView.backgroundColor = [UIColor colorWithWhite:0.95 alpha:1];
    _buttonsScrollView.showsHorizontalScrollIndicator = NO;
    NSArray *imageNames = @[@"水族论坛",@"宠物论坛", @"钓具论坛",@"旅游论坛"];
    for (NSInteger i = 0; i < 4; i++) {
//        HomeSectionView *view = [[HomeSectionView alloc] initWithFrame:CGRectMake(i * SCREEN_WIDTH / 4, 0, SCREEN_WIDTH / 4, SCREEN_WIDTH / 5) type:ZKHomeSectionViewTypeV2];
        ForcumHomeView *view = [[ForcumHomeView alloc] initWithFrame:CGRectMake(i * SCREEN_WIDTH / 4, 0, SCREEN_WIDTH / 4, SCREEN_WIDTH / 5) mulriple:0.4];
        view.tag = i;
        view.title = imageNames[i];
        view.imgName= imageNames[i];
        view.backgroundColor = [UIColor clearColor];
        view.titleColor = rgba(12, 91, 158, 1);
        [_buttonsScrollView addSubview:view];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(_tapAction:)];
        [view addGestureRecognizer:tap];

    }
    [_scrollView addSubview:_buttonsScrollView];
}
// 创建表视图
- (void)_initTableView {
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, _buttonsScrollView.bottom, SCREEN_WIDTH, 0) style:UITableViewStylePlain];
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.scrollEnabled = NO;
//    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_scrollView addSubview:_tableView];
    
    
    
    // 设置表视图高度
    //    _tableView.height = (kCellHeight + kHeaderHeight) * sections;
    
    // 注册单元格
    [_tableView registerClass:[ShowCell class] forCellReuseIdentifier:@"ShowCell"];
}


#pragma mark - UITableViewDataSource UITableViewDelegate
// 设置组数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
// 设置行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _itemsAry.count;
}
// 设置单元格属性
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ShowCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ShowCell"];
    
    // 填充数据
    ShowCellLayout *layout = _itemsAry[indexPath.row];
    cell.layout = layout;
    
    return cell;
    
}
// 设置单元格行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ShowCellLayout *layout = _itemsAry[indexPath.row];
    return layout.cellRect.size.height;
}
// 设置组尾高度
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 1;
}
// 设置组头高
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 1;
}

// 单元格点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    PostDetailVC *vc = [[PostDetailVC alloc] init];
    ShowCellLayout *layout = _itemsAry[indexPath.row];
    vc.fid = layout.model.fid;
    vc.tid = layout.model.tid;
    [self.navigationController pushViewController:vc animated:YES];
}



#pragma mark - 点击事件
// 导航栏右侧按钮（搜索和消息通知）
- (void)_naviRightAction:(UIButton *)button {
  
//    SearchPostVC *vc = [[SearchPostVC alloc] init];
//    [self.navigationController pushViewController:vc animated:YES];
    switch (button.tag) {
        case 1:
        {
            //消息页的跳转
            ShopMessageVC *vc = [[ShopMessageVC alloc] init];
            vc.fromNum = @"1";
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case 2:
        {
            SearchPostVC *vc = [[SearchPostVC alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
            
        default:
            break;
    }

    
}
// 导航栏左侧按钮（返回和发表）
- (void)_naviLeftAction:(UIButton *)button {
    [self leftAction:nil];
}
// 森森智囊团
- (void)_recruitModeratorAction:(UITapGestureRecognizer *)tap {
    ForumSectionVC *vc = [[ForumSectionVC alloc] init];
    vc.naviTitle = @"森森智囊团";
    vc.fid = @"3";
    [self.navigationController pushViewController:vc animated:YES];
}
// 森森设计师
- (void)_showAndAwardAction:(UITapGestureRecognizer *)tap {
    ForumSectionVC *vc = [[ForumSectionVC alloc] init];
    vc.naviTitle = @"森森设计师";
    vc.fid = @"8";
    [self.navigationController pushViewController:vc animated:YES];
    
}
// 森森采购师
- (void)_postAndCouponsAction:(UITapGestureRecognizer *)tap {
    ForumSectionVC *vc = [[ForumSectionVC alloc] init];
    vc.naviTitle = @"森森采购师";
    vc.fid = @"7";
    [self.navigationController pushViewController:vc animated:YES];
}
//购物评论区
- (void)_shoppingAction:(UITapGestureRecognizer *)tap{
    ForumSectionVC *vc = [[ForumSectionVC alloc] init];
    vc.naviTitle = @"购物评论区";
    vc.fid = @"15";
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)_tapAction:(UITapGestureRecognizer *)tap{
    if (tap.view.tag == 0) {
        WaterForumSectionVC *vc = [[WaterForumSectionVC alloc] init];
        vc.naviTitle = @"水族论坛";
        ForumModel *model = [[ForumModel alloc] init];
        vc.fid = @"1";
        if (_nameAry.count >= 1) {
            model = _nameAry[0];
            vc.fid = model.fid;
        }
        vc.subForumAry = [_nameAry mutableCopy];
//        ForumSectionVC *vc = [[ForumSectionVC alloc] init];
//        vc.naviTitle = @"水族论坛";
//        vc.fid = @"1";
        [self.navigationController pushViewController:vc animated:YES];
    }
    if (tap.view.tag == 1) {
        ForumSectionVC *vc = [[ForumSectionVC alloc] init];
        vc.naviTitle = @"宠物论坛";
        vc.fid = @"2";
        [self.navigationController pushViewController:vc animated:YES];
    }
    if (tap.view.tag == 2) {
        ForumSectionVC *vc = [[ForumSectionVC alloc] init];
        vc.naviTitle = @"钓具论坛";
        vc.fid = @"4";
        [self.navigationController pushViewController:vc animated:YES];
    }
    if (tap.view.tag == 3) {
        ForumSectionVC *vc = [[ForumSectionVC alloc] init];
        vc.naviTitle = @"旅游论坛";
        vc.fid = @"6";
        [self.navigationController pushViewController:vc animated:YES];
    }

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
